import datetime
import logging
import os
import sys

from common.utils import root_path


def logFile(fileName='接口测试', output='all'):
    # 设置路径
    now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')
    path_file = root_path() + r'\log\{}_{}.log'.format(fileName, now_time).replace(r'\/'.replace(os.sep, ''), os.sep)
    # 设置日志器
    log = logging.getLogger()
    # coloredlogs.install(level='INFO',
    #                     fmt='[%(asctime)s]：[%(levelname)s]->>%(message)s',
    #                     )

    log.setLevel(level=logging.INFO)
    # 设置格式器
    streanFormatter = logging.Formatter(fmt='[%(filename)s]:[%(asctime)s]：[line:%(lineno)d][%(levelname)s]->>%(message)s')
    fileFormatter = logging.Formatter(fmt='[%(filename)s]:[%(levelname)s][%(asctime)s]''line:%(lineno)d->>%(message)s',
                                      datefmt='%H:%M:%S')
    # 设置控制台处理器
    s_hand = logging.StreamHandler()
    # s_hand.setLevel(logging.WARNING)  # 设置处理器级别
    s_hand.setFormatter(streanFormatter)  # 添加控制台格式器
    # 设置文件处理器
    f_hand = logging.FileHandler(filename=path_file, encoding='utf-8')
    # f_hand.setLevel(logging.INFO)  # 设置处理器级别
    f_hand.setFormatter(fileFormatter)  # 添加文件格式器

    if output == "all":
        # 日志器添加控制台处理器
        log.addHandler(s_hand)
        # 日志器添加文件处理器
        log.addHandler(f_hand)
        return log
    elif output == 'stream':
        log.addHandler(s_hand)
        return log
    elif output == 'file':
        log.addHandler(f_hand)
        return log
    else:
        raise ValueError("output参数错误")



if __name__ == '__main__':
    log = logFile('数据测试')
    log.warning('adasfasdf')
    log.info('test1')
    # from loguru import logger
    # logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")
    # logger.add(sys.stderr, colorize=True, format="<green>{time}</green> <level>{message}</level>")
    # def log(fileName='接口测试'):
    #     fmt = "{time} - {name} - {level} - {message}"
    #     now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')
    #     path_file = rootDir + r'\log\{}_{}.log'.format(fileName, now_time).replace(r'\/'.replace(os.sep, ''), os.sep)
    #     logger.add(f"{path_file}.log", level="INFO", format=fmt)
    #     # logger.add(sys.stderr, level="WARNING", format=fmt)
    #
    #     logger.info('test1234')
    # # For libraries
    #     logger.warning('bad hav')
    #     logger.info("No matter added sinks, this message is not displayed")
    #
    #     logger.info("This message however is propagated to the sinks")
    # log()
    # @logger.catch
    # def my_function(x, y, z):
    #     # An error? It's caught anyway!
    #     return 1 / (x + y + z)
    # a = my_function(1,2,3)
    # print(a)
    # from loguru import logger
    #
    #
    # def some_func(a, b):
    #     if a < 0:
    #         logger.warning("Oh no!")
    #     return a + b


    # import pytest
    # from loguru import logger
    # from _pytest.logging import LogCaptureFixture
    #
    #
    # @pytest.fixture
    # def caplog(caplog: LogCaptureFixture):
    #     handler_id = logger.add(
    #         caplog.handler,
    #         format="{message}",
    #         level=0,
    #         filter=lambda record: record["level"].no >= caplog.handler.level,
    #         enqueue=False,  # Set to 'True' if your test is spawning child processes.
    #     )
    #     yield caplog
    #     logger.remove(handler_id)
    #
    #     import pytest
    #     from loguru import logger
    #
    #     @pytest.fixture
    #     def reportlog(pytestconfig):
    #         logging_plugin = pytestconfig.pluginmanager.getplugin("logging-plugin")
    #         handler_id = logger.add(logging_plugin.report_handler, format="{message}")
    #         yield
    #         logger.remove(handler_id)

    # def test_some_func(caplog):
    #     assert some_func(-1, 3) == 2
    #     assert "Oh no!" in caplog.text